﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrienDev.Data;

namespace FrienDev.BusinessRules
{
    public class VisitorRules
    {
        public static VisitorRules Instance = new VisitorRules();

        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private VisitorRules()
        {
        }

        public void AddVisitor(string userId)
        {
            string visitorId = UserRules.Instance.GetCurrentUserId();
            Visitor visitor = (from v in m_DataContext.Visitors
                               where v.UserId == userId && v.VistorId == visitorId
                               select v).SingleOrDefault();
            if (visitor != null)
            {
                visitor.LastVisitDateTime = DateTime.Now;
            }
            else
            {
                visitor = new Visitor
                {
                    UserId = userId,
                    VistorId = UserRules.Instance.GetCurrentUserId(),
                    LastVisitDateTime = DateTime.Now
                };
                m_DataContext.Visitors.InsertOnSubmit(visitor);
            }
            m_DataContext.SubmitChanges();
            IEnumerable<Visitor> visitors = from v in m_DataContext.Visitors
                                            where v.UserId == userId
                                            orderby v.LastVisitDateTime descending
                                            select v;
            if (visitors.Count() > 50)
            {
                m_DataContext.Visitors.DeleteOnSubmit(visitors.First());
                m_DataContext.SubmitChanges();
            }
        }

        #region by cciel

        /// <summary>
        /// 获得最近访问好友列表——by cciel
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="amount">获取个数,-1为所有</param>
        /// <returns></returns>
        public IEnumerable<User> GetRecentVisitorListByUserId(string userId, int amount)
        {
            IEnumerable<User> visitors = from visit in m_DataContext.Visitors
                                         where visit.UserId == userId
                                         orderby visit.LastVisitDateTime descending
                                         join user in m_DataContext.Users on visit.VistorId equals user.UserId
                                         select user;
            if (amount != -1)
            {
                return visitors.Take(amount);//最近访问的人
            }
            return visitors;
        }


        #endregion
    }
}
